<template>
	<u-upload
		:fileList="fileList"
		@afterRead="afterRead"
		@delete="deletePic"
		name="1"
		multiple
		width="70"
		height="70"
		:maxSize="maxSize"
		:maxCount="maxCount"
		style="width: 140rpx; height: 140rpx"
	>
		<slot></slot>
	</u-upload>
</template>

<script>
import { uploadCdnParams } from "@/utils/tools"
import { $uploadFile } from "@/api/lv-app"

const ONE_MB = 1 * 1024 * 1024

export default {
	name: "AppUpload",
	props: {
		maxCount: {
			type: Number,
			default: 9,
		},
		maxSize: {
			type: Number,
			default: ONE_MB,
		},
	},
	data() {
		return {
			fileList: [],
		}
	},
	methods: {
		// 删除图片
		deletePic(event) {
			this[`fileList`].splice(event.index, 1)
			this.$emit("input", this.fileList)
		},
		// 新增图片
		async afterRead(event) {
			// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file)
			let fileListLen = this[`fileList`].length
			lists.map((item) => {
				this[`fileList`].push({
					...item,
					status: "uploading",
					message: "上传中",
				})
			})
			for (let i = 0; i < lists.length; i++) {
				const result = await this.uploadFilePromise(lists[i].url)
				let item = this[`fileList`][fileListLen]
				this[`fileList`].splice(
					fileListLen,
					1,
					Object.assign(item, {
						status: "success",
						message: "",
						url: result,
					})
				)
				fileListLen++
			}
			this.$emit("input", this.fileList)
		},
		uploadFilePromise(url) {
			return new Promise((resolve, reject) => {
				let imgBase64 = this.convertToBase64(url),
					timestamp = Math.floor(new Date().getTime() / 1000),
					fileExt = url
						.split("/")
						.pop()
						.match(/\.([^.]+)$/)[1]

				let { query, post } = uploadCdnParams(imgBase64, timestamp + "." + fileExt, timestamp)

				$uploadFile(query, post).then((data) => {
					resolve(data)
				})
			})
		},
		convertToBase64(filePath) {
			const base64Img = uni.getFileSystemManager().readFileSync(filePath, "base64") //转码
			// return 'data:image/png;base64,' + base64Img //拼接后返回
			return base64Img //拼接后返回
		},
	},
}
</script>
